package com.hansheng.ssdxs.ui.fragment;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.google.android.material.tabs.TabLayout;
import com.hansheng.ssdxs.R;
import com.hansheng.ssdxs.base.BaseFragment;
import com.hansheng.ssdxs.base.ViewInject;
import com.xuexiang.xui.widget.toast.XToast;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * ---------------------------------------------------------------
 * 作者：HanSheng
 * 邮箱：164897033@qq.com
 * 创建时间：2020/12/5  17:02
 * 文件描述：首页
 * ---------------------------------------------------------------
 */
@ViewInject(mainlayoutid = R.layout.fragment_main_home)
public class FragmentMainHome extends BaseFragment implements TabLayout.OnTabSelectedListener{

    @BindView(R.id.TabLayout)
    TabLayout tabLayout;
    @BindView(R.id.ViewPager)
    ViewPager viewPager;

    private String[] titles = {"最新","热门","我的"};
    private ArrayList<Fragment> fragments = new ArrayList<>();
    private VpAdapter vpAdapter;

    @Override
    public void afterBindView() {
        init();
        XToast.error(mContext,"选择了：");
    }

    private void init(){
        for(int i=0;i<titles.length;i++){
            fragments.add(new FragmentMainHomeTab());
            tabLayout.addTab(tabLayout.newTab());
        }

        tabLayout.setupWithViewPager(viewPager,false);
        vpAdapter = new VpAdapter(getChildFragmentManager(),fragments);
        viewPager.setAdapter(vpAdapter);
        // 设置标题
        for(int i=0;i<titles.length;i++){
            tabLayout.getTabAt(i).setText(titles[i]);
        }

        tabLayout.addOnTabSelectedListener(this);
    }

    @Override
    public void onTabSelected(TabLayout.Tab tab) {
        XToast.info(mContext,"选择了："+tab.getText());
    }

    @Override
    public void onTabUnselected(TabLayout.Tab tab) {

    }

    @Override
    public void onTabReselected(TabLayout.Tab tab) {

    }

    /**
     * view pager adapter
     */
    private static class VpAdapter extends FragmentPagerAdapter {
        private List<Fragment> data;

        public VpAdapter(FragmentManager fm, List<Fragment> data) {
            super(fm);
            this.data = data;
        }

        @Override
        public int getCount() {
            return data.size();
        }

        @Override
        public Fragment getItem(int position) {
            return data.get(position);
        }
    }
}
